package com.example.socket.heatBeat;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.*;
import java.net.*;

public class HeartbeatClient {
    public static void main(String[] args)  throws Exception{
        heatBeatClient();
    }

    public static void heatBeatClient(){
        try {
            // 创建Socket并连接服务器
            Socket socket = new Socket("localhost", 8000);
            System.out.println("Connected to server");

            // 创建输入输出流
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();

            // 定义心跳消息
            String heartbeatMsg = "heartbeat";

            // 每隔5秒钟发送一次心跳消息
            while (true) {
                // 发送心跳消息
                outputStream.write(heartbeatMsg.getBytes());
                outputStream.flush();

                // 等待服务器响应，超时时间为5秒钟
                socket.setSoTimeout(5000);
                try {
                    byte[] responseBytes = new byte[1024];
                    int length = inputStream.read(responseBytes);
                    String responseMsg = new String(responseBytes, 0, length);
                    System.out.println("Received response: " + responseMsg);
                } catch (SocketTimeoutException e) {
                    // 超时未收到响应，说明连接已断开
                    System.out.println("Connection lost");
                    break;
                }

                // 暂停5秒钟
                Thread.sleep(5000);
            }

            // 关闭Socket和流
            outputStream.close();
            inputStream.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void tel()  {
        TelnetClient telnetClient = new TelnetClient();
        while (true){
            try {
                Thread.sleep(5000);
                telnetClient.connect("192.168.137.113",8081);
                System.out.println("已正常连接");
               /* InputStream in = telnetClient.getInputStream();
                OutputStream os = telnetClient.getOutputStream();
                // 读取到login:停止
                System.out.println(readUntil(":", in) + "liang");
                // 代填账号
                writeUtil("liang", os);
                // 读取到Password:停止
                System.out.println(readUntil(":", in) + "123");
                // 代填密码
                writeUtil("123", os);
                // 读取到Last login:停止表示登陆成功
                String result = readUntil("Last login:", in);
                if(result.endsWith("Last login:")){
                    System.out.println("登陆成功");
                }else{
                    System.out.println("登陆失败");
                }
                in.close();
                os.close();*/
                telnetClient.disconnect();
            } catch (Exception e) {
                System.out.println("==========~连接失败~==========");

            }
        }
    }

    /**
     * 写入命令方法
     * @param cmd
     * @param os
     */
    public static void writeUtil(String cmd, OutputStream os){
        try {
            cmd = cmd + "\n";
            os.write(cmd.getBytes());
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 读到指定位置,不在向下读
     * @param endFlag
     * @param in
     * @return
     */
    public static String readUntil(String endFlag, InputStream in) {
        InputStreamReader isr = new InputStreamReader(in);
        char[] charBytes = new char[1024];
        int n = 0;
        boolean flag = false;
        String str = "";
        try {
            while((n = isr.read(charBytes)) != -1){
                for(int i=0; i< n; i++){
                    char c = (char)charBytes[i];
                    str += c;
                    //当拼接的字符串以指定的字符串结尾时,不在继续读
                    if(str.endsWith(endFlag) || str.endsWith("Login incorrect")){
                        flag = true;
                        break;
                    }
                }
                if(flag){
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

}